package com.test.web.excel.listener;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.he.core.excle.listener.DefaultReadListener;
import com.test.web.excel.data.wz.ReadGoodsData;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author heyanjing
 * date:2020-05-08 2020/5/8:9:55
 * 复写DefaultReadListener
 */
@Slf4j
@Data
public class WzReadListener extends DefaultReadListener<ReadGoodsData> {
    private List<ReadGoodsData>  data   = new ArrayList<>();
    private Map<Integer, Object> header = new HashMap<>(10);
    /**
     * 解析表头，多行表头会执行多次
     */
    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {
        Integer rowIndex = context.readRowHolder().getRowIndex();
        log.info("解析第{}行头信息：{}", rowIndex, JSONUtil.toJsonStr(headMap));
        headMap.forEach((integer, cellData) -> {
            CellDataTypeEnum type = cellData.getType();
            Object val;
            switch (type) {
                case NUMBER:
                    val = cellData.getNumberValue();
                    break;
                case BOOLEAN:
                    val = cellData.getBooleanValue();
                    break;
                case STRING:
                case DIRECT_STRING:
                    val = cellData.getStringValue();
                    break;
                case EMPTY:
                case ERROR:
                    val = "";
                    break;
                default:
                    val = "";
                    break;
            }
            header.put(integer, val);
        });
        log.info("第{}行完整头内容 {}", rowIndex, JSONUtil.toJsonStr(header));
    }
    /**
     * 这个每一条数据解析都会来调用
     */
    @Override
    public void invoke(ReadGoodsData t, AnalysisContext analysisContext) {
        Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
        log.info("解析第{}行数据：{}", rowIndex, JSONUtil.toJsonStr(t));
        if (StringUtils.isNotBlank(t.getName()) && t.getPrice() != null) {
            data.add(t);
        }
    }
}
